/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package vzone.community;

import java.util.ArrayList;
import vzone.tools.Date;
import java.util.Iterator;
import java.util.UUID;
import java.util.logging.Level;
import java.util.logging.Logger;
import vzone.bank.Bank;
import vzone.job.Jobs;
import vzone.tools.SqlHelper;
import vzone.structs.BasePeople;
import vzone.structs.Housing;
import vzone.structs.Job;
import vzone.structs.OperatorCode;
import vzone.tools.MD5;

/**
 *
 * @author Kingpro
 */
public class Community implements ICommunity
{

    private static final String INSERT_PEOPLE = "INSERT INTO [c_people] ([peopleId], [accountId], [name], [nickName], [gender], [birthday], [pwdHash], [picIndex]) VALUES(?,?,?,?,?,?,?,?)";
    //登录时根据昵称查询数据库
    private static final String SELECT_PEOPLE = "SELECT * FROM  [c_people] WHERE [nickName]=? AND [pwdHash]=?";
    //根据人的idJob字段来查询人对应的工作信息
    private static final String UPDATE_PWD = "UPDATE people SET pwdHash=@pwd WHERE nickName=@name";
    //CheckPeopleInfo中使用
    private static final String CHECK_PEOPLE = "SELECT * FROM  [c_people] WHERE [peopleId]=?";
    private static final String TESTNICKNAME = "SELECT * FROM [c_people] WHERE [nickName]=?";
    private static Community community = new Community();

    public static Community getCommunity()
    {
	return community;
    }

    /**
     * OK
     * @param people
     * @param pwdHashS
     * @return
     */
    @Override
    public OperatorCode Register(BasePeople people, String pwdHashS)
    {
	try
	{
	    OperatorCode code = TestNickName(people.NickName);
	    if (code != OperatorCode.SUCCESS)
	    {
		return code;
	    }
	    people.PeopleIdUuid = UUID.randomUUID();
	    SqlHelper.ExecuteNonQuery(
		    SqlHelper.getConnect(),
		    INSERT_PEOPLE,
		    new Object[]
		    {
			people.PeopleIdUuid.toString(),
			Bank.getBank().CreateAccount(people, pwdHashS).toString(),
			people.NameS,
			people.NickName,
			people.GenderB ? 1 : 0,
			people.BirthdayD,
			MD5.getMD5(pwdHashS),
			people.PicI
		    });
	    return OperatorCode.SUCCESS;
	}
	catch (Exception ex)
	{
	    return OperatorCode.OTHER_ERROR;
	}
    }

    /**
     * OK
     * @param nicknameS
     * @return
     */
    public OperatorCode TestNickName(String nicknameS)
    {
	try
	{
	    Object object = SqlHelper.ExecuteScalar(SqlHelper.getConnect(), TESTNICKNAME, "nickName", new Object[]
		    {
			nicknameS
		    });
	    if (object == null)
	    {
		return OperatorCode.SUCCESS;
	    }
	    return OperatorCode.INVALIEDNICKNAME;
	}
	catch (Exception ex)
	{
	    return OperatorCode.OTHER_ERROR;
	}
    }

    /**
     * OK
     * @param NickNameS
     * @param pwdHash
     * @param people
     * @return
     */
    @Override
    public OperatorCode Login(String NickNameS, String pwdHash, BasePeople people)
    {
	ArrayList resultAl = null;
	try
	{
	    resultAl = SqlHelper.ExecuteReader(SqlHelper.getConnect(), SELECT_PEOPLE, new Object[]
		    {
			NickNameS,
			MD5.getMD5(pwdHash)
		    });
	}
	catch (Exception ex)
	{
	    return OperatorCode.OTHER_ERROR;
	}
	if (resultAl.size() == 0)
	{
	    return OperatorCode.NOPEOPLE;
	}

	Object[] resultOs = (Object[]) resultAl.get(0);

	people.PeopleIdUuid = UUID.fromString(resultOs[0].toString());
	people.accountIdUuid = UUID.fromString(resultOs[2].toString());

	people.NameS = (String) resultOs[3];
	people.NickName = NickNameS;
	people.GenderB = (Boolean) resultOs[5];
	people.BirthdayD=Long.parseLong(resultOs[6].toString());
	people.PicI = Integer.parseInt(resultOs[8].toString());
	if (resultOs[1] != null)
	{
	    Job job = new Job();
	    if (Jobs.getJobs().GetJobInfo(UUID.fromString(resultOs[1].toString()), job) == OperatorCode.SUCCESS)
	    {
		people.JobJ = job;
	    }
	}
	return OperatorCode.SUCCESS;
    }

    @Override
    public OperatorCode ChangePwd(UUID peopleIDUuid, String oldpwdHashS, String newpwdHash)
    {
	throw new UnsupportedOperationException("Not supported yet.");
    }

    @Override
    public OperatorCode ChangePwd(String NickNameS, String oldpwdHashS, String newpwdHash)
    {
	ArrayList resultAl = null;

	try
	{
	    resultAl = SqlHelper.ExecuteReader(SqlHelper.getConnect(), SELECT_PEOPLE, new Object[]
		    {
			NickNameS
		    });
	}
	catch (Exception ex)
	{
	    Logger.getLogger(Community.class.getName()).log(Level.SEVERE, null, ex);
	}
	Iterator<Object> resultI = resultAl.iterator();

	if (resultI.hasNext())
	{
	    //用户存在
	    while (resultI.hasNext())
	    {
		Object[] resultOs = (Object[]) resultI.next();
		if (oldpwdHashS == resultOs[7])
		{
		    //update
		    try
		    {
			SqlHelper.ExecuteNonQuery(SqlHelper.getConnect(), UPDATE_PWD, new Object[]
				{
				    newpwdHash, NickNameS
				});
		    }
		    catch (Exception ex)
		    {
			Logger.getLogger(Community.class.getName()).log(Level.SEVERE, null, ex);
		    }
		}
	    }
	}
	else
	{
	    //提示用户不存在
	}
	return OperatorCode.INVALIEDPWD;//密码错误
    }

    @Override
    public boolean CheckPeopleInfo(UUID peopleID)
    {
	ArrayList resultAl = null;

	try
	{
	    resultAl = SqlHelper.ExecuteReader(SqlHelper.getConnect(), CHECK_PEOPLE, new Object[]
		    {
			peopleID
		    });
	}
	catch (Exception ex)
	{
	    Logger.getLogger(Community.class.getName()).log(Level.SEVERE, null, ex);
	}
	if (resultAl == null)
	{
	    return false;
	}
	else
	{
	    return true;
	}

    }
/**
 * OK
 * @param peopleID
 * @return
 */
    @Override
    public BasePeople GetPeopleInfo(UUID peopleID)
    {
	ArrayList resultAl = new ArrayList();
	BasePeople people = new BasePeople();
	try
	{
	    resultAl = SqlHelper.ExecuteReader(SqlHelper.getConnect(), CHECK_PEOPLE, new Object[]
		    {
			peopleID.toString()
		    });
	}
	catch (Exception ex)
	{
	    return null;
	}
	if (resultAl.size() == 0)
	{
	    return null;
	}
	Object[] resultOs = (Object[]) resultAl.get(0);
	people.PeopleIdUuid = UUID.fromString((String) resultOs[0]);
	people.accountIdUuid = UUID.fromString((String) resultOs[2]);
	Job job = new Job();
	if (resultOs[1]!=null && Jobs.getJobs().GetJobInfo(UUID.fromString((String) resultOs[1]), job) == OperatorCode.SUCCESS)
	{
	    people.JobJ = job;
	}
	people.NameS = (String) resultOs[3];
	people.NickName = (String) resultOs[4];
	people.GenderB = (Boolean) resultOs[5];
	people.BirthdayD=Long.parseLong(resultOs[6].toString());
	people.PicI=Integer.parseInt(resultOs[8].toString());
	return people;
    }

    @Override
    public OperatorCode sellHouse(Housing house, int sellingPrice)
    {
	throw new UnsupportedOperationException("Not supported yet.");
    }

    @Override
    public OperatorCode rentHouse(Housing house, int rentPrice, boolean perYear)
    {
	throw new UnsupportedOperationException("Not supported yet.");
    }

    /**
     * 判断必要信息是否完整（注册时）
     * @param people
     * @param pwdHashS
     * @return
     */
    private boolean infoFull(BasePeople people, String pwdHashS)
    {
	if (people.NameS != null && people.accountIdUuid != null && people.NickName != null && pwdHashS != null)
	{
	    return true;
	}
	return false;
    }

    private boolean accountExits(BasePeople people)
    {
	//暂时不处理
	return true;
    }

    private boolean pwdLegal(String pwdHashS)
    {
	//暂时不处理
	return true;
    }
}
